// component.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { JsonApiService } from "app/core/api/json-api.service";
import { config } from '../../shared/smartadmin.config';

declare var $: any;
declare var Viewer: any;
@Component({
    selector: 'sa-bad-record',
    templateUrl: './bad-record.component.html',
    styleUrls: ['./bad-record.css']
})
export class BadRecordComponent implements OnInit {
    tableData: any = []; // table的表单数据
    totalCounts: number = 0; //分页总条数
    curPage: number = 1; //分页当前页
    pageSize: number = 10; //内置的分页每页条数
    // 查询参数
    selectedCompanyId: any = ""; // 公司的id
    selectedCompanyName: any = ""; // 公司的名称
    startTime: any = ""; // 开始时间
    endTime: any = ""; // 结束时间
    searchKey: any = ""; // 用户的搜索关键字
    isCheck: any = ""; //检测状态
    retestResult: any = ""; //复测结果
    joinRepairedRecordFlag: any = ""; //是否关联维修记录
    joinzhiJuFlag: any = ""; //是否关联治具检测

    constructor(private router: Router, private activatedRoute: ActivatedRoute, private jsonApiService: JsonApiService) {
        activatedRoute.queryParams.subscribe(queryParams => {
        });
    }
    ngOnInit() {
        this.initDate();
        this.initDateTc();
        this.load();
    }


    // 时间选择回调
    dateSelect(time) {
        this.startTime = time.startTime;
        this.endTime = time.endTime;
    }
    // 初始化1天的时间
    initDate() {
        // let nowTime = new Date();
        // this.endTime = common.getTimeMmss(nowTime);
        // nowTime.setDate(nowTime.getDate() - 30);
        // this.startTime = common.getTimeMmss(nowTime);
        this.specifyTime = {
            startTime: this.startTime,
            endTime: this.endTime,
        }
    }
    specifyTime: any;

    //公司选中回调
    companySelected(data) {
        this.selectedCompanyId = data.companyId;
        this.selectedCompanyName = data.companyName;
    }

    // 获取列表数据
    load() {
        let param = {
            "pageSize": this.pageSize,
            "nowPage": this.curPage,
            "parameters": {
                companyId: this.selectedCompanyId,
                startTime: this.startTime,
                endTime: this.endTime,
                searchKey: common.stringTrim(this.searchKey),
                isCheck: this.isCheck,
                retestResult: this.retestResult,
                joinRepairedRecordFlag: this.joinRepairedRecordFlag,
                joinzhiJuFlag: this.joinzhiJuFlag,
                export: '0'
            }
        }
        let reqdata = 'gridPager=' + JSON.stringify(param);
        this.jsonApiService.http("deviceRepaired/list.html", reqdata).subscribe(result => {
            let data = []
            if (result.isSuccess && result.exhibitDatas) {
                data = result.exhibitDatas

                this.tableData = result.exhibitDatas
                this.totalCounts = result.recordCount;
            }
        });
    }

    // 分页回调
    paginate(e) {
        this.curPage = e.page + 1;
        this.pageSize = e.rows;
        this.load();
    }
    // 刷新表
    refresh() {
        this.load();
    }
    // 表单查询
    tableSearch() {
        this.curPage = 1;
        this.load();
    }
    /**
     * 图片查看的方法
     */
    imgList: any = [];
    imgLocalList: any = [];
    isViewer2: boolean = false; //默认隐藏
    //显示图片组件
    viewer2: any = '';
    showImg2(row, modal) {

        this.imgList = [];
        this.imgLocalList = [];
        if (row.imagePaths.indexOf(',') > 1) {
            this.imgList = row.imagePaths.split(',');
        } else {
            this.imgList.push(row.imagePaths);
        }


        let localImg;
        for (var i = 0; i < this.imgList.length; i++) {
            if (this.imgList[i].indexOf('http') == -1) {
                if (this.imgList[i][0] == '/') {
                    localImg = config.BaseURL + this.imgList[i].substr(1);
                } else {
                    localImg = config.BaseURL + this.imgList[i];
                }
            } else {
                localImg = this.imgList[i];
            }
            this.imgLocalList.push(localImg);
        }
        modal.show();

        if (this.isViewer2 && $(".viewer-container").length > 0) {
            this.viewer2.destroy();
        }
    }
    // 关闭图片查看
    closeImgModal2(modal) {
        modal.hide();
        this.imgList = [];
        this.imgLocalList = [];
    }
    //图片放大
    bigimg(type, row) {
        this.showBigImg(type);
    }
    showBigImg(type) {
        var that = this;
        var imgList
        if (type == 'Modal2') {
            imgList = $(".imagesInfo2")[0];
            this.viewer2 = new Viewer(imgList, {
                url: 'src',
                title: function (image) {
                    return image.alt + ' (' + (this.index + 1) + '/' + this.length + ')';
                },
            });
            that.isViewer2 = true
        }
    }


    //初始化日期
    initDateTc() {
        var that = this;
        var date = new Date();
        System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(
            () => {
                System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
                    $("#returnTime").datetimepicker({//时间插件
                        format: "yyyy-mm-dd hh:ii:ss",
                        language: "zh-CN",
                        autoclose: true,
                    }).on("changeDate", function (e) {
                        var date = e.date;
                        if (!date) { return; }
                        var time = common.getTimeMmss(date);
                        that.recordDetailFrom.returnTime = time;
                    });

                    $("#productTime").datetimepicker({//时间插件
                        format: "yyyy-mm-dd hh:ii:ss",
                        language: "zh-CN",
                        autoclose: true,
                    }).on("changeDate", function (e) {
                        var date = e.date;
                        if (!date) { return; }
                        var time = common.getTimeMmss(date);
                        that.recordDetailFrom.productTime = time;
                    });

                    $("#resolutionTime").datetimepicker({//时间插件
                        format: "yyyy-mm-dd hh:ii:ss",
                        language: "zh-CN",
                        autoclose: true,
                    }).on("changeDate", function (e) {
                        var date = e.date;
                        if (!date) { return; }
                        var time = common.getTimeMmss(date);
                        that.recordDetailFrom.resolutionTime = time;
                    });
                });
            });
    }

    pageType: any = '新增'
    //编辑
    edtrRecord(row, modal) {
        //清除数据
        this.repairedSublist = []
        this.fixtureSublist = []
        this.searchData = ''
        this.type = '1'
        for (let key in this.recordDetailFrom) {
            this.recordDetailFrom[key] = ''
        }
        this.pageType = '编辑';
        for (let key in this.recordDetailFrom) {
            this.recordDetailFrom[key] = row[key] ? row[key] : '';
        }
        if (this.recordDetailFrom.imagePaths) {
            this.imageInfoList = this.recordDetailFrom.imagePaths.split(',');
        } else {
            this.imageInfoList = [];
        }
        if (row.deviceBadRepaired) {
            let obj = {
                carNumber: row.deviceBadRepaired.carNumber,
                companyId: row.deviceBadRepaired.companyId,
                companyName: row.deviceBadRepaired.companyName,
                deviceId: row.deviceBadRepaired.deviceId,
                faultPhenomenonList: row.deviceBadRepaired.faultPhenomenon,
                id: row.deviceBadRepaired.repairedId,
                repairSubdivideList: row.deviceBadRepaired.repairedSubdivide,
                repairedTime: row.deviceBadRepaired.repairedTime,
                repairedType: row.deviceBadRepaired.repairedType,
                repairedUserName: row.deviceBadRepaired.repairedUser,
                warrantyExpirationTime: row.deviceBadRepaired.warrantyExpirationTime,
                expire: row.deviceBadRepaired.expire
            }
            this.repairedSublist.push(obj)
            this.recordDetailFrom.isConnectRepaired = 1
        }
        if (row.deviceBadCheck) {
            let obj = {
                checkMen: row.deviceBadCheck.checkMen,
                checkTime: row.deviceBadCheck.checkTime,
                zhiJuId: row.deviceBadCheck.zhiJuId,
                zhiJuResult: row.deviceBadCheck.zhiJuResult
            }
            this.fixtureSublist.push(obj)
        }
        modal.show()
    }
    deleteRecord(row) {
        this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(() => {
            this.jsonApiService.http("deviceRepaired/deleteDeviceBadRecordById.html", 'id=' + row.id).subscribe(data => {
                this.jsonApiService.message(data.message);
                if (data.success) {
                    this.load();
                }
            })
        })
    }


    //新增 操作
    recordDetailFrom: any = {
        id: '',
        returnTime: '',
        carNumber: '',
        companyName: '',
        companyId: '',
        deviceId: '',
        productNo: '',
        productTime: '',
        hwVersion: '',
        badReasons: '',
        improvementStrategy: '',
        resolutionTime: '',
        principal: '',
        imagePaths: '',
        faultPhenomenon: '',
        repairedId: '',
        zhiJuId: '',
        iccid: '',
        retestResult: '', //复测结果
        retestRemark: '', //复测结果备注
        isConnectRepaired: 1 //默认已关联
    }
    // 新增不良记录
    addRecordDetail(modal) {
        this.pageType = '新增';
        for (let key in this.recordDetailFrom) {
            this.recordDetailFrom[key] = ''
        }
        this.recordDetailFrom.isConnectRepaired = 1
        this.searchData = ''
        this.type = '2'
        this.recordDetailFrom.returnTime = common.getTimeMmss(new Date());
        this.imageInfoList = [];
        this.fixtureSublist = []; //治具检测清空
        this.repairedSublist = [];//维修记录清空
        modal.show();
        setTimeout(() => {
            this.initCarSelect2()
            this.del_carNumber()
            $('#carNumberSelect2').val('').trigger('change')
        }, 200)
    }
    // 车辆组件数据回调
    optionSelected(data) {
        this.recordDetailFrom.repairedId = ''
        this.recordDetailFrom.zhiJuId = ''
        if (data && (data.id || data.text)) {
            this.recordDetailFrom.carNumber = data.text;
            this.recordDetailFrom.deviceId = data.id;
            this.recordDetailFrom.companyName = data.option ? data.option.parentName : '';
            this.recordDetailFrom.repairedId = ''
            if (this.recordDetailFrom.deviceId.trim()) {
                this.getDeviceBaseDataV2();
            }
        } else {
            this.recordDetailFrom.carNumber = '';
            this.recordDetailFrom.deviceId = '';
            this.recordDetailFrom.companyName = '';
            this.repairedSublist = []
            this.fixtureSublist = []
        }
        $("#deviceIdFrom").val(data.id ? data.id : '');
        $("#deviceIdFrom").trigger("change");
    }
    // 获取设备信息
    getDeviceBaseDataV2() {
        this.fixtureSublist = []; //治具检测清空
        this.repairedSublist = [];//维修记录清空
        this.recordDetailFrom.zhiJuId = ''
        let searchValue = ''
        if (this.pageType == '编辑') {
            searchValue = '?deviceId=' + this.recordDetailFrom.deviceId + '&repairedId=' + this.recordDetailFrom.repairedId + "&isConnectRepaired=" + this.recordDetailFrom.isConnectRepaired
        } else {
            if (this.recordDetailFrom.repairedId) {
                searchValue = '?deviceId=' + this.recordDetailFrom.deviceId + '&repairedId=' + this.recordDetailFrom.repairedId + "&isConnectRepaired=" + this.recordDetailFrom.isConnectRepaired
            } else {
                if (this.type == '3') {
                    searchValue = '?productNo=' + this.searchData + '&repairedId=' + this.recordDetailFrom.repairedId + "&isConnectRepaired=" + this.recordDetailFrom.isConnectRepaired
                } else {
                    searchValue = '?deviceId=' + this.searchData + '&repairedId=' + this.recordDetailFrom.repairedId + "&isConnectRepaired=" + this.recordDetailFrom.isConnectRepaired
                }
            }
        }

        this.jsonApiService.http_get('deviceRepaired/getHostBaseInfo.html' + searchValue).subscribe(data => {
            if (data.success) {
                this.recordDetailFrom.companyId = data.data.companyId;
                this.recordDetailFrom.companyName = data.data.companyName;
                this.recordDetailFrom.carNumber = data.data.carNumber;
                this.recordDetailFrom.deviceId = data.data.deviceId;

                this.recordDetailFrom.productNo = data.data.productNo;
                this.recordDetailFrom.productTime = data.data.productTime;
                this.recordDetailFrom.hwVersion = data.data.hwVersion;
                this.recordDetailFrom.repairedId = data.data.repairedId //关联维修记录ID
                this.recordDetailFrom.faultPhenomenon = data.data.faultPhenomenonStr; //故障现象
                this.recordDetailFrom.iccid = data.data.iccid
                if (data.data.repairedId) {
                    let obj = {
                        carNumber: data.data.carNumber,
                        companyId: data.data.companyId,
                        companyName: data.data.companyName,
                        deviceId: data.data.deviceId,
                        faultPhenomenonList: data.data.faultPhenomenon,
                        id: data.data.repairedId,
                        repairSubdivideList: data.data.repairedSubdivide,
                        repairedTime: data.data.repairedTime,
                        repairedType: data.data.repairedType,
                        repairedUserName: data.data.repairedUser,
                        warrantyExpirationTime: data.data.warrantyExpirationTime,
                        expire: data.data.expire
                    }
                    this.repairedSublist.push(obj)
                }
                if (data.data.zhiJuId) {
                    let obj = {
                        checkMen: data.data.checkMen,
                        checkTime: data.data.checkTime,
                        zhiJuResult: data.data.zhiJuResult
                    }
                    this.recordDetailFrom.zhiJuId = data.data.zhiJuId
                    this.fixtureSublist.push(obj)
                }
            } else {
                this.jsonApiService.message(data.message);
            }
        })
    }
    recordDetailClose(modal) {
        for (let key in this.recordDetailFrom) {
            this.recordDetailFrom[key] = ''
        }
        modal.hide()
    }
    recordDetailSubmit(modal) {
        var Url;
        if (this.pageType == '新增') {
            Url = 'deviceRepaired/add.html'
        } else if (this.pageType == '编辑') {
            Url = 'deviceRepaired/updateDeviceBadRecord.html'
        }
        this.recordDetailFrom.faultPhenomenon = this.recordDetailFrom.faultPhenomenon.trim()
        this.recordDetailFrom.deviceId = this.recordDetailFrom.deviceId.trim()
        this.recordDetailFrom.returnTime = $('#returnTime').val()
        this.recordDetailFrom.productTime = $('#productTime').val()
        this.recordDetailFrom.resolutionTime = $('#resolutionTime').val()
        if (!this.recordDetailFrom.returnTime) {
            this.jsonApiService.message('寄回时间不能为空');
            return
        }
        if (!this.recordDetailFrom.deviceId) {
            this.jsonApiService.message('设备ID不能为空');
            return
        }
        if (!this.recordDetailFrom.retestResult) {
            this.jsonApiService.message('复测结果不能为空')
            return
        }
        if (!this.recordDetailFrom.faultPhenomenon) {
            this.jsonApiService.message('复测故障现象不能为空');
            return
        }
        this.recordDetailFrom.imagePaths = this.imageInfoList.join(',');
        let reqdata = JSON.parse(JSON.stringify(this.recordDetailFrom))
        this.jsonApiService.http_obj(Url, reqdata).subscribe(data => {
            this.jsonApiService.message(data.message);
            if (data.success) {
                this.load();
                modal.hide()
            }
        })
    }


    imageInfoList: any = []; //图片数组
    fileList: File = null;
    //上传多张
    multifileChange(files: FileList) {
        if (this.isViewer && $(".viewer-container").length > 0) {
            this.viewer.destroy();
        }

        var that = this;
        let multfileList = files;

        var reqdata = new FormData();
        reqdata.append('describe', '不良记录');
        reqdata.append('businessType', '1');
        // reqdata.append('deviceId', this.page.deviceId);
        reqdata.append('type', '2'); //type 1获取相对路径  2获取绝对路径

        for (var i = 0; i < multfileList.length; i++) {
            this.fileList = multfileList[i];
            const isJPG = this.fileList.type === 'image/jpeg' || this.fileList.type === 'image/jpg' || this.fileList.type === 'image/png';
            if (!isJPG) {
                this.jsonApiService.message('上传图片只能是 png, jpg, jpeg 格式!');
                return;
            }

            reqdata.append('files', multfileList[i]);

        }

        that.jsonApiService.form_http("fileUpload/upload.html", reqdata).subscribe(data => {
            if (data.success) {
                for (var i = 0; i < data.data.length; i++) {
                    that.imageInfoList.push(data.data[i]);
                }
            }
        })


        for (let k = 0; k < $(".up").length; k++) {
            $(".up")[k].value = null;
        }

    }
    //删除
    deleteImg(i) {
        this.imageInfoList.splice(i, 1);

        if (this.isViewer && $(".viewer-container").length > 0) {
            this.viewer.destroy();
        }
    }
    bigImg: any = '' //
    isViewer: boolean = false; //默认隐藏
    bigImgClick(img) {
        // modal.show();
        this.bigImg = img;
        if (this.isViewer && $(".viewer-container").length > 0) {
            System.import('assets/js/viewer/viewer.js').then(
                () => {
                    System.import('assets/js/viewer/bootstrap.bundle.min.js').then(
                        () => {
                            System.import('assets/js/viewer/viewer.css').then(() => {
                                this.showImg();
                            })
                        })
                })
        } else {
            this.showImg();
        }


    }
    //显示图片组件
    viewer: any = '';
    showImg() {
        var that = this;
        var imgList = $(".imgFileList")[0];
        this.viewer = new Viewer(imgList, {
            url: 'src',
            title: function (image) {
                return image.alt + ' (' + (this.index + 1) + '/' + this.length + ')';
            },
        });
        that.isViewer = true
    }



    //导出
    dataExceport() {
        if (!this.startTime || !this.endTime) {
            this.jsonApiService.message('请先选择时间')
            return
        }
        var data: any, Url: string;
        Url = 'deviceRepaired/list.html';
        data = {
            "pageSize": this.pageSize,
            "nowPage": this.curPage,
            "parameters": {
                companyId: this.selectedCompanyId,
                startTime: this.startTime,
                endTime: this.endTime,
                searchKey: common.stringTrim(this.searchKey),
                isCheck: this.isCheck,
                joinRepairedRecordFlag: this.joinRepairedRecordFlag,
                retestResult: this.retestResult,
                joinzhiJuFlag: this.joinzhiJuFlag,
                export: '1' //是否导出
            }
        }
        let timeCheck = common.correctTime(data.parameters, ['export'])
        if (!timeCheck.status) {
            this.jsonApiService.message(timeCheck.message);
            return;
        }
        common.exprotDataFile(data, 'gridPager', config.BaseURL + Url)
    }
    /**
     * 已维修弹窗
     */
    repairedListData: any = [] //已维修列表数据
    repairedSelected: any = []; //已维修勾选数据
    repairedSublist: any = [] //确定提交的维修数据
    //新增已维修列表弹窗
    addBadRecord(modal) {
        if (!this.recordDetailFrom.deviceId) {
            this.jsonApiService.message("请选择车牌或输入设备ID");
            return;
        } else {
            modal.show()
            this.jsonApiService.http_obj("deviceRepaired/queryRecentDeviceRepairedRecordV2.html", { 'deviceId': this.recordDetailFrom.deviceId, 'id':this.recordDetailFrom.id  }).subscribe(result => {
                this.repairedListData = result.data;
                this.repairedSelected = []
                for (let item of this.repairedListData) {
                    if (item.id === this.recordDetailFrom.repairedId) {
                        item['isChecked'] = true;
                        this.repairedSelected.push(item)
                    } else {
                        item['isChecked'] = false;
                    }
                }
            });
        }
    }
    //table复选框数据row选中事件回调:处理选中状态和deviceId
    rowSelected(row, e, index) {
        if (row.isChecked) {
            row.isChecked = false;
            this.repairedSelected.forEach((el, i) => {
                if (el.id === row.id) {
                    this.repairedSelected.splice(i, 1);
                }
            })
        } else {
            row.isChecked = true;
            this.repairedSelected.push(row);
        }
    }
    //确认提交已维修列表弹窗
    recordFaultPhenomenonSubmit(modal) {
        if (this.repairedSelected.length == 0) {
            this.jsonApiService.message("请勾选至少一条数据");
            return;
        }
        if (this.repairedSelected.length > 1) {
            this.jsonApiService.message("请选择一条数据添加,暂不支持多条数据添加");
            return;
        }
        this.repairedSublist = JSON.parse(JSON.stringify(this.repairedSelected))
        this.recordDetailFrom.repairedId = this.repairedSelected[0].id;
        this.recordDetailFrom.faultPhenomenon = this.repairedSelected[0].faultPhenomenonList.join(',');
        this.recordDetailFrom.isConnectRepaired = 1
        this.getDeviceBaseDataV2() //维修记录变更 重新请求接口
        this.addBadRecordClose(modal);
    }
    //关闭已维修列表弹窗
    addBadRecordClose(modal) {
        modal.hide();
    }
    //点击维修未关联
    notBadRecord(modal1) {
        this.recordDetailFrom.faultPhenomenon = ''
        this.recordDetailFrom.repairedId = ''
        this.repairedSublist = []
        this.recordDetailFrom.isConnectRepaired = 0
        modal1.hide()
        this.getDeviceBaseDataV2() //维修记录变更 重新请求接口
    }


    /**
     * 治具弹窗
     */
    fixtureListData: any = [] //治具弹窗列表数据
    fixtureSelected: any = []; //治具勾选数据
    fixtureSublist: any = [] //提交的治具数据
    //新增治具列表弹窗
    addFixtureRecord(modal) {
        if (!this.recordDetailFrom.deviceId) {
            this.jsonApiService.message("请选择车牌或输入设备ID");
            return;
        } else {
            modal.show()
            this.jsonApiService.http_obj("deviceRepaired/getZhiJuLogDataByDeviceId.html",
                { 'deviceId': this.recordDetailFrom.deviceId, 'repairedId': this.recordDetailFrom.repairedId }).subscribe(result => {
                    this.fixtureSelected = []
                    this.fixtureListData = result.data;
                    for (let item of this.fixtureListData) {
                        if (item.zhiJuId === this.recordDetailFrom.zhiJuId) {
                            item['isChecked'] = true;
                            this.fixtureSelected.push(item)
                        } else {
                            item['isChecked'] = false;
                        }
                    }
                });
        }
    }
    //table复选框数据row选中事件回调:处理选中状态和deviceId
    rowFixtureSelected(row, e, index) {
        if (row.isChecked) {
            row.isChecked = false;
            this.fixtureSelected.forEach((el, i) => {
                if (el.zhiJuId === row.zhiJuId) {
                    this.fixtureSelected.splice(i, 1);
                }
            })
        } else {
            row.isChecked = true;
            this.fixtureSelected.push(row);
        }
    }
    //关闭治具弹窗
    fixtureModalClose(modal) {
        modal.hide()
    }
    //提交治具弹窗
    fixtureModalSubmit(modal) {
        if (this.fixtureSelected.length == 0) {
            this.jsonApiService.message("请勾选至少一条数据");
            return;
        }
        if (this.fixtureSelected.length > 1) {
            this.jsonApiService.message("请选择一条数据添加,暂不支持多条数据添加");
            return;
        }
        this.fixtureSublist = JSON.parse(JSON.stringify(this.fixtureSelected))
        this.recordDetailFrom.zhiJuId = this.fixtureSelected[0].zhiJuId;
        this.fixtureModalClose(modal);
    }
    //点击维修未关联
    notFixtureRecord(modal1) {
        this.recordDetailFrom.zhiJuId = ''
        this.fixtureSublist = []
        modal1.hide()
    }
    type: string = '2' //类型 1 设备  2车牌 3外壳编码
    searchDataList: any = [] //查询列表
    searchData: string = ' '
    //查询请求
    searchValue() {
        if (!this.searchData) {
            this.jsonApiService.message("请输入模糊搜索框里面的内容");
            return
        }
        if (this.searchData.length < 4) {
            return
        }
        $('#carNumberSelect2').val(this.searchData).trigger('change');
        this.recordDetailFrom.deviceId = '' //清空原有的设备id
        this.recordDetailFrom.repairedId = '' //清空原有的维修id
        this.recordDetailFrom.isConnectRepaired = 1 //默认查询已关联的数据
        this.getDeviceBaseDataV2() //维修记录变更 重新请求接口
    }
    //改变查询类型
    changeType(value) {
        this.type = value
        this.searchData = ''
        //采用简单粗暴的方法清除;官方推荐的方法失效
        var str = $("<span class='select2-selection__placeholder'>请选择</span>");
        $('#carNumberSelect2').val("");
        $("#select2-carNumberSelect2-container").empty();
        $("#select2-carNumberSelect2-container").attr("title", "");
        $("#select2-carNumberSelect2-container").prepend(str);
    }
    // 擦除车牌号码所选值
    del_carNumber() {
        this.searchData = ''
        //采用简单粗暴的方法清除;官方推荐的方法失效
        var str = $("<span class='select2-selection__placeholder'>请选择</span>");
        $('#carNumberSelect2').val("");
        $("#select2-carNumberSelect2-container").empty();
        $("#select2-carNumberSelect2-container").attr("title", "");
        $("#select2-carNumberSelect2-container").prepend(str);
    }
    //首次加载
    initCarSelect2() {
        System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
            System.import('assets/js/select2-zh-CN.js').then(() => {
                this.initSelect2()
            });
        });
    }
    // 初始化select2配置
    initSelect2() {
        var that = this;
        $("#carNumberSelect2").select2({
            language: "zh-CN",
            placeholder: "请选择",
            allowClear: true,
            minimumInputLength: 4, //最少4个字符，select2才显示查询的内容
            ajax: {
                url: config.BaseURL + 'deviceRepaired/getDeviceBadSelectInfo.html',
                dataType: 'json',
                delay: 50,
                method: "POST",
                xhrFields: {
                    withCredentials: true
                },
                data: function (params) {
                    return {
                        "content": params.term,
                        "type": that.type // search term
                    };
                },
                processResults: function (data, params) {
                    var options = new Array();
                    const dataList = JSON.parse(JSON.stringify(data.data))
                    dataList.forEach(el => {
                        if (that.type == '1') {
                            options.push({
                                'id': el.deviceId,
                                'text': el.deviceId
                            })
                        }
                        if (that.type == '2') {
                            options.push({
                                'id': el.deviceId,
                                'text': el.carNumber + '(' + el.deviceId + ')'
                            })
                        }
                        if (that.type == '3') {
                            options.push({
                                'id': el.productNo,
                                'text': el.productNo
                            })
                        }
                    })
                    return {
                        results: options //获取查询后的结果
                    };
                },
                cache: true
            },
            templateResult: this.formatRepo
        }).on("select2:select", function (e) {
            that.searchData = e.params.data.id
            console.log(e.params.data, 'e.params.data')
        });
    }
    //select2 格式回调函数
    formatRepo(state) {
        if (!state.id) {
            return state.text
        };
        var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>');
        return $state;
    }
}